package com.net.xpay.web.controller.merchant;

import com.alipay.api.AlipayApiException;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.xpay.alipay.PoseidonAlipayClient;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.helper.RedisHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.constant.RedisKey;
import com.net.xpay.core.domain.AlipayUser;
import com.net.xpay.core.enums.AlipayUserStatus;
import com.net.xpay.core.manager.AlipayUserManager;
import com.net.xpay.core.model.AlipayUserSearchModel;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@Slf4j
@RequestMapping("/merchant/alipay")
@Api(tags = "商户/支付宝授权", description = "商户 支付宝授权 net")
public class AlipayAuthController {

    @Autowired
    private PoseidonAlipayClient xpayAlipayClient;

    @Autowired
    private AlipayUserManager alipayUserManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private RedisHelper redisHelper;


    /**
     * 获取支付宝授权页面, 可进行签约
     * @param alipayNickName 支付宝账号
     */
    @ApiOperation(value = "跳转支付宝签约页面")
    @GetMapping("/go-auth-page")
    @ResponseBody
    public ResultData<Void> goAuthPage(@ApiIgnore @RequestUser User user, HttpServletResponse response, String alipayNickName) throws AlipayApiException {
        if (Strings.isNullOrEmpty(alipayNickName)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入支付宝账号");
        }
        //先从缓存中查，如果没有再请求新的
        Object authUrl = redisHelper.get(RedisKey.AUTH_ALIPAY_USER_URL + ":" + user.getId() + ":" + alipayNickName);
        if (authUrl != null) {
            try {
                AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(user.getId(), alipayNickName);
                if (alipayUser != null) {
                    alipayUser.setIsDeleted(0);
                    alipayUserManager.updateByPrimaryKeyWithVersion(alipayUser);
                }
                response.sendRedirect(authUrl.toString());
            } catch (IOException e) {
                log.error("goAuthPage redirect error(cache url)|alipayNickName={}", alipayNickName, e);
            }
            return new ResultData<>();
        }

        Long userId = user.getId();
        String isvBizId = userId + "-" + System.currentTimeMillis();
        String authPageUrl = xpayAlipayClient.alipayOpenInviteOrderCreate(isvBizId, alipayNickName);
        AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(userId, alipayNickName);
        if (alipayUser == null) {
            alipayUser = AlipayUser.getInstance();
            alipayUser.setUserId(userId);
            alipayUser.setMobile(user.getMobile());
            alipayUser.setAlipayNickName(alipayNickName);
            // 异步消息需要根据isvBizId来获取对应token
            alipayUser.setIsvBizId(isvBizId);
            alipayUser.setStatus(AlipayUserStatus.NO);
            alipayUser.setIsDeleted(0);
            alipayUserManager.save(alipayUser);

            //将第一个绑定的号作为主支付宝账号
            AlipayUserSearchModel searchModel = new AlipayUserSearchModel();
            searchModel.setUserId(user.getId());
            long count = alipayUserManager.searchCount(searchModel);
            if (count == 1L) {
                User selectedUser = userManager.getById(user.getId());
                selectedUser.setAlipayNickName(alipayNickName);
                selectedUser.setAlipayUserId(alipayUser.getId());
                userManager.updateByPrimaryKeyWithVersion(selectedUser);
            }
        } else {
            alipayUser.setStatus(AlipayUserStatus.NO);
            alipayUser.setIsvBizId(isvBizId);
            alipayUser.setIsDeleted(0);
            alipayUserManager.updateByPrimaryKeyWithVersion(alipayUser);
        }
        redisHelper.set(RedisKey.AUTH_ALIPAY_USER_URL + ":" + user.getId() + ":" + alipayNickName, authPageUrl, 60 * 30L);
        try {
            response.sendRedirect(authPageUrl);
        } catch (IOException e) {
            log.error("goAuthPage redirect error|alipayNickName={}", alipayNickName, e);
        }
        return new ResultData<>();
    }
}
